import axios from 'axios'
import router from '@/router'
import { Message, Loading, Notification } from 'element-ui'

let loading

const http = axios.create({
  timeout: 1000 * 30,
  withCredentials: true,
  headers: {
    //     [{"username":"jx"},{"username":"cc"}]
    //   "?username=jx&password=123456"
    //   "<xml><username>jx</username><password>123456</password></xml>"
    // 注意 设置这个  就代表该axios只能发送json了.不能发送form结构了  比如 ?username=jx&password=123456
    'Content-Type': 'application/json; charset=utf-8'
  }
})

function startLoading () {
  loading = Loading.service({
    lock: true,
    text: '加载中...',
    background: 'rgba(0, 0, 0, 0.7)'
  })
}

function endLoading () {
  loading.close()
}

/**
 * 请求拦截
 */
http.interceptors.request.use(config => {
  //let url = config.url.substr(0, 11)
  if (localStorage.getItem('token') != null) {
    config.headers['Authorization'] = localStorage.getItem('token') // 请求头带上token
  }
  return config
  startLoading()
  if (localStorage.getItem('token') != null) {
    config.headers['Authorization'] = 'Bearer '+localStorage.getItem('token') // 请求头带上token
  }
  return config
}, error => {
  return Promise.reject(error)
})

/**
 * 响应拦截
 */
http.interceptors.response.use(response => {
  //endLoading()
  if (response.headers.token) {//如果返回的消息头中有token，就更新token
    localStorage.setItem("token", response.headers.token)
    location.reload()
  }
  if (response.data.state === 99999) {//设置异常号
    //debugger
    Notification.error({ title: '错误', message: '未知错误！！去控制台看', duration: 2500 })
    localStorage.removeItem('token')
    this.$router.go(-1)
  }
  return response
}, error => {
  return Promise.reject(error)
})
export default http


